<template>
  <div class="app-wrap">
    <div :class="['nav-wrap', isFull ? 'mini' : '']">
      <nav :class="['menu-nav', isFull ? 'mini' : '']">
        <div class="app-title">
          <div class="logo-wrap">
            <img src="../assets/images/logo.jpg" />
          </div>
          <!-- <img src="../assets/images/logo_c.png" /> -->
        </div>
        <div class="menu-wrap">
          <el-menu
            background-color="#545c64"
            text-color="#ADADAD"
            active-text-color="#4AC493"
            :default-active="$route.path"
            class="nav-list"
            :collapse="showMenu"
            unique-opened
            @select="handleSelect"
            :router="true"
          >
            <el-menu-item class="home" index="/home">
              <i class="el-icon-s-home sold icon-common"></i>
              <span slot="title">首页</span>
            </el-menu-item>

            <el-submenu
              class="user"
              v-for="(item, i) in authList"
              :key="i"
              :index="'' + i + 2"
            >
              <template slot="title">
                <i :class="['sold', 'icon-common', item.icon]"></i>
                <span slot="title">{{item.label}}</span>
              </template>
              <el-menu-item
                v-for="(menu, index) in item.children"
                :key="index"
                :index="menu.path"
              >
                {{menu.label}}
              </el-menu-item>
              <!-- <el-menu-item v-if="!(roleId === 2)" index="/user/admin">管理用户</el-menu-item>
              <el-menu-item index="/user/client">注册用户</el-menu-item>
              <el-menu-item index="/user/authority">权限管理</el-menu-item> -->
            </el-submenu>

            <!-- <el-submenu v-if="roleId !== 3" class="message" index="3">
              <template slot="title">
              <i class="el-icon-message-solid sold icon-common"></i>
                <span slot="title">消息管理</span>
              </template>
              <el-menu-item index="/message/service">服务类消息</el-menu-item>
              <el-menu-item index="/message/system">系统消息</el-menu-item>
            </el-submenu>

            <el-submenu v-if="roleId !== 3" class="file" index="4">
              <template slot="title">
              <i class="el-icon-s-order sold icon-common"></i>
                <span slot="title">健康档案管理</span>
              </template>
              <el-menu-item index="/chart/category">表类目管理</el-menu-item>
              <el-menu-item index="/file/all">健康档案总表维护</el-menu-item>
              <el-menu-item index="/file/data">数据维护</el-menu-item>
              <el-menu-item index="/file/grade">Z评分设置维护</el-menu-item>
              <el-menu-item index="/file/bmi">BMI设置维护</el-menu-item>
            </el-submenu>

            <el-submenu v-if="roleId !== 3" class="test" index="5">
              <template slot="title">
              <i class="el-icon-s-platform sold icon-common"></i>
                <span slot="title">健康评测</span>
              </template>
              <el-menu-item index="/test/rule">健康评测规则设置</el-menu-item>
              <el-menu-item index="/test/price">健康评测价格设置</el-menu-item>
            </el-submenu>

            <el-submenu v-if="roleId !== 3" class="template" index="6">
              <template slot="title">
                <i class="el-icon-menu sold icon-common"></i>
                <span slot="title">模板设置</span>
              </template>
              <el-menu-item index="/template/setting">AI模板设置</el-menu-item>
              <el-menu-item index="/template/search">AI模板查询</el-menu-item>
              <el-menu-item index="/template/paper/setting">调查问卷模板设置</el-menu-item>
              <el-menu-item index="/template/paper/search">调查问卷模板查询</el-menu-item>
            </el-submenu>

            <el-submenu v-if="roleId === 3 || !(roleId === 2)" class="money" index="7">
              <template slot="title">
                <i class="el-icon-picture sold icon-common"></i>
                <span slot="title">图片管理</span>
              </template>
              <el-menu-item index="/image">成员上传图片管理</el-menu-item>
            </el-submenu>

            <el-submenu v-if="roleId !== 3" class="product" index="8">
              <template slot="title">
                <i class="el-icon-s-tools sold icon-common"></i>
                <span slot="title">产品设置</span>
              </template>
              <el-menu-item index="/product/diet">健康食谱设置</el-menu-item>
              <el-menu-item index="/product/storage">存储空间设置</el-menu-item>
            </el-submenu>

            <el-submenu class="count" index="9">
              <template slot="title">
                <i class="el-icon-s-marketing sold icon-common"></i>
                <span slot="title">统计分析</span>
              </template>
              <el-menu-item index="/statistics/consume">用户消费统计</el-menu-item>
              <el-menu-item index="/member/statistics">学校统计</el-menu-item>
              <el-menu-item index="/temperature">体温打卡</el-menu-item>
              <el-menu-item index="/statistics/temperature">体温打卡统计</el-menu-item>
              <el-menu-item index="/statistics/mental">心理统计</el-menu-item>
              <el-menu-item index="/buried-point" disabled>页面埋点统计</el-menu-item>
            </el-submenu>

            <el-submenu v-if="roleId === 3 || !(roleId === 2)" class="money" index="10">
              <template slot="title">
                <i class="el-icon-s-finance sold icon-common"></i>
                <span slot="title">财务管理</span>
              </template>
              <el-menu-item index="/finance/income">收支查询</el-menu-item>
            </el-submenu>

            <el-submenu v-if="roleId === 3 || !(roleId === 2)" class="money" index="11">
              <template slot="title">
                <i class="el-icon-s-data sold icon-common"></i>
                <span slot="title">销售统计</span>
              </template>
              <el-menu-item index="/sale/list">销售员列表</el-menu-item>
            </el-submenu>

            <el-submenu v-if="roleId === 3 || !(roleId === 2)" class="money" index="12">
              <template slot="title">
                <i class="el-icon-s-cooperation sold icon-common"></i>
                <span slot="title">疫苗管理</span>
              </template>
              <el-menu-item index="/vaccine">疫苗列表</el-menu-item>
            </el-submenu>

            <el-submenu v-if="roleId === 3 || !(roleId === 2)" class="money" index="13">
              <template slot="title">
                <i class="el-icon-s-management sold icon-common"></i>
                <span slot="title">心理健康管理</span>
              </template>
              <el-menu-item index="/test/mental_question">心理健康题库管理</el-menu-item>
              <el-menu-item index="/test/mental">心理健康测试表管理</el-menu-item>
            </el-submenu>

            <el-submenu index="14">
              <template slot="title">
                <i class="el-icon-s-operation sold icon-common"></i>
                <span slot="title">东北师大接口测试</span>
              </template>
              <el-menu-item disabled index="/for_test">学校测试管理</el-menu-item>
            </el-submenu>

            <el-submenu index="15">
              <template slot="title">
                <i class="el-icon-s-flag sold icon-common"></i>
                <span slot="title">知识管理</span>
              </template>
              <el-menu-item index="/article/list">文章管理</el-menu-item>
            </el-submenu> -->

            <!-- <el-submenu v-if="roleId === 3 || !(roleId === 2)" class="money" index="13">
              <template slot="title">
                <i style="font-size: 26px; margin-right: 8px;" class="el-icon-s-order vaccine"></i>
                <span slot="title">体温打卡</span>
              </template>
              <el-menu-item index="/temperature">体温打卡列表</el-menu-item>
            </el-submenu> -->

            <!-- <el-submenu v-if="roleId === 3 || !(roleId === 2)" class="money" index="14">
              <template slot="title">
                <i style="font-size: 26px; margin-right: 8px;" class="el-icon-s-data vaccine"></i>
                <span slot="title">用户行为管理</span>
              </template>
              <el-menu-item index="/buried-point" disabled>用户行为记录</el-menu-item>
            </el-submenu> -->

            <!-- <el-submenu v-if="roleId === 3 || !(roleId === 2)" class="money" index="15">
              <template slot="title">
                <i style="font-size: 26px; margin-right: 8px;" class="el-icon-s-data vaccine"></i>
                <span slot="title">添加测评结果模板</span>
              </template>
              <el-menu-item index="/result/template">添加测评结果模板</el-menu-item>
            </el-submenu> -->
          </el-menu>
        </div>
      </nav>
    </div>
    <div :class="['container', isFull ? 'full' : '']">
      <div class="header">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item v-for="(item, i) in paths" :key="i">{{item}}</el-breadcrumb-item>
        </el-breadcrumb>
        <div style="display: flex; align-items: center;">
          <!-- <el-switch style="margin-right: 30px;" v-model="openLight" @change="handleLight"></el-switch> -->
          <i :class="['full-screen', isFull ? 'el-icon-s-unfold' : 'el-icon-s-fold']" @click="switchFull"></i>
          <el-dropdown @command="handleClickMenu">
            <div class="admin el-dropdown-link">
              <img class="m-r" src="../assets/images/avatar.png" />
              <span class="f-s-m pointer">{{admin.name}}</span>
              <img src="../assets/images/down.png" />
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="setting">账号设置</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <div class="content">
        <keep-alive>
          <router-view v-if="$route.meta.keepAlive"></router-view>
        </keep-alive>
        <!-- <router-view v-else="!$route.meta.keepAlive"></router-view> -->
        <router-view v-if="!$route.meta.keepAlive"></router-view>
      </div>
    </div>
    <el-dialog title="修改密码" :visible.sync="showDialog">
      <el-form :model="user" :rules="rules" ref="pass">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input type="password" show-password v-model="user.oldPassword" />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input type="password" show-password v-model="user.password" />
        </el-form-item>
        <el-form-item label="确认新密码" prop="aginPass">
          <el-input type="password" show-password v-model="user.aginPass" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="updatePass('pass')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getAdmin,
  updatePassword,
  getAuthByRoleId,
  updatePasswordV2
} from '../api';
import { notifySuccess, authList2Tree } from '../util'

export default {
  name: 'layout',
  data () {
    const validatePass = (rules, value, callback) => {
      if (!value) {
        return callback(new Error('该项不能为空'))
      }
      if (value !== this.user.password) {
        return callback(new Error('两次密码不一致'))
      }
      callback()
    };
    const validateNewPass = (rules, value, callback) => {
      if (!value) {
        return callback(new Error('该项不能为空'))
      };
      if (value.length < 6 || value.length > 15) {
        return callback(new Error('密码长度在 6 至 15个字符之间'))
      };
      if (!isNaN(value)) {
        return callback(new Error('密码不能为纯数字'))
      };
      callback()
    };
    return {
      showMenu: false,
      showDialog: false,
      roleId: 1,
      openLight: true,
      paths: [],
      authList: [],
      isFull: false,
      fullAuthList: [],
      rules: {
        password: [
          { required: true, validator: validateNewPass, trigger: 'blur' }
        ],
        oldPassword: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        aginPass: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ]
      },
      user: {
        password: '',
        oldPassword: '',
        aginPass: ''
      },
      admin: {
        name: ''
      }
    }
  },
  methods: {
    handleSelect () {
      // console.log(arguments)
    },
    switchFull () {
      this.isFull = !this.isFull
    },
    updatePass (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          let userId = sessionStorage.getItem('uuid');
          let userName = sessionStorage.getItem('username');
          updatePasswordV2({
            userId,
            userName,
            passwrod: this.user.password,
            oldPassword: this.user.oldPassword
          })
          .then(res => {
            if (res.data.code === 1) {
              // notifySuccess(this)
              this.$message({
                type: 'success',
                message: '密码修改成功! 即将强制退出系统, 请重新登录!',
                onClose: () => {
                  sessionStorage.clear()
                  this.$router.push('/login')
                }
              })
            } else {
              this.$message.error(res.data.msg || '网络异常!')
            }
          })
          .catch(e => {
            this.$message.error('网络异常!')
          })
        } else {
          return false
        }
      })
    },
    fetchAuthByRoleId (roleId) { // 根据角色id查询权限
      getAuthByRoleId(roleId)
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || [];
          let curPath = this.$route.path;
          let tempObj = {};
          list.forEach(item => {
            if (item.userPermissionType === '1') {
              tempObj[item.userPermissionUrl] = list.filter(a => a.parentId == item.userPermissionId).map(b => b.userPermissionValue)
            }
          });
          this.fullAuthList = tempObj;
          let curAuth = tempObj[curPath];
          this.$store.commit('setCurAuth', curAuth);
          this.authList = authList2Tree(list);
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    handleLight (val) {
      let html = document.documentElement;
      html.style.filter = val ? '' : 'hue-rotate(120deg)'
    },
    handleClickMenu (command) {
      if (command === 'logout') {
        sessionStorage.clear();
        this.$router.push('/login')
      } else if (command === 'setting') {
        this.$notify({
          title: '操作提示',
          message: '修改密码成功后, 将强制退出系统! 在此之前请确保所操作业务已保存完毕',
          duration: 5000
        })
        this.showDialog = true
      }
    },
    fetchAdminInfo () {
      getAdmin()
      .then(res => {
        if (res.data.code === 1) {
          this.admin = res.data.data
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    }
  },
  created () {
    let roleId = sessionStorage.getItem('role');
    this.fetchAuthByRoleId(roleId);
    this.admin.name = sessionStorage.getItem('username');
    this.$store.commit('setUserName', this.admin.name);
    this.paths = this.$route.meta.path
    let role = sessionStorage.getItem('role')
    if (!role) {
      this.$message.error('登录状态异常! 请重新登录')
      this.$router.push('/login')
    } else {
      this.roleId = Number(role)
    }
  },
  watch: {
    $route () {
      this.paths = this.$route.meta.path;
      let curPath = this.$route.path;
      let curAuth = this.fullAuthList[curPath];
      // console.error('页面权限列表', curAuth)
      this.$store.commit('setCurAuth', curAuth);
    }
  }
}
</script>
<style lang="scss">
  // @import url('../assets/icon/iconfont.css');
  .app-wrap {
    position: relative;
    height: 100%;
    .icon-common {
      margin-right: 8px;
      font-size: 22px!important;
    }
    .menu-nav {
      width: 200px;
      transition: all .6s;
      overflow-x: hidden;
      &.mini {
        width: 0px;
      }
    }
    .full-screen {
      color: #cccccc;
      font-size: 30px;
      cursor: pointer;
      margin-right: 20px;
    }
    .nav-wrap {
      position: fixed;
      top: 0;
      left: 0;
      bottom: 0;
      width: 200px;
      height: 100%;
      overflow-y: auto;
      overflow-x: hidden;
      transition: all .6s;
      background-color: #545C64;
      &::-webkit-scrollbar {
        display: none;
      }
      &.mini {
        width: 0px;
      }
      .app-title {
        position: sticky;
        top: 0;
        height: 160px;
        z-index: 1;
        background-color: #545C64;
        text-align: center;
        .logo-wrap {
          position: absolute;
          top: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 100px;
          height: 100px;
          // background-color: $main-color;
          img {
            width: 100%;
            height: 100%;
            border-bottom-left-radius: 50px;
            border-bottom-right-radius: 50px;
            box-shadow: 0 8px 15px #242424;
            // animation: rotate infinite 1.5s ease-in-out;
          }
          @keyframes rotate {
            from { transform: rotateZ(0deg) }
            to { transform: rotateZ(360deg) }
          }
        }
      }
      .nav-list {
        border: none;
      }
    }
    .container {
      position: relative;
      height: 100%;
      margin-left: 200px;
      transition: all .6s;
      &.full {
        margin-left: 0;
      }
      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 25px;
        width: 100%;
        height: 60px;
        background-color: #363636;
        position: sticky;
        top: 0;
        z-index: 99;
        .admin {
          display: flex;
          align-items: center;
          color: #ADADAD;
        }
      }
    }
    .el-breadcrumb {
      span {
        color: $main-color!important;
        font-size: 12px;
      }
    }
    .menu-icon {
      display: inline-block;
      width: 22px;
      height: 22px;
      // background-image: url('../assets/images/icon.png');
      &.home { background-position: -334px -3px; }
      &.user { background-position: -154px -3px; }
      &.message { background-position: -455px -5px; }
      &.file { background-position: -365px -6px; }
      &.test { background-position: -275px -4px; }
      &.template { background-position: -35px -3px; }
      &.image { background-position: -575px -4px; }
      &.product { background-position: -65px -5px; }
      &.count { background-position: -394px -3px; }
      &.money { background-position: -95px -5px; }
    }
    .el-submenu__title { border-left: 2px solid transparent; color: #ffffff; }
    .is-active {
      i.home { background-position: -544px -3px }
      i.user { background-position: -185px -4px; }
      i.message { background-position: -485px -5px; }
      i.file { background-position: -305px -6px; }
      i.test { background-position: -215px -4px; }
      i.template { background-position: -245px -3px; }
      i.product { background-position: -5px -5px; }
      i.image { background-position: -515px -4px; }
      i.count { background-position: -424px -3px; }
      i.money { background-position: -125px -5px; }
      i.sold { color: $main-color; }
      i.vaccine { color: $main-color; }
      .el-submenu__title {
        border-color: $main-color;
        span {
          color: $main-color;
        }
      }
    }
    .el-menu-item {
      padding-left: 50px!important;
      &.home { border-left: 2px solid transparent; padding-left: 20px!important; }
      &.image { border-left: 2px solid transparent; padding-left: 20px!important; }
      &.home.is-active { border-color: $main-color; }
      &.image.is-active { border-color: $main-color; }
    }
  }
</style>
